package com.mw.controller;

import com.mw.domain.Comment;
import com.mw.domain.News;
import com.mw.domain.User;
import com.mw.service.CommentService;
import com.mw.service.NewsService;
import com.mw.service.UserService;
import com.mw.util.StringTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    CommentService commentService;
    @Autowired
    NewsService newsService;
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public String toUserById(@PathVariable("id") String id,ModelMap map){
        User user = userService.getUserById(Integer.valueOf(id));
        map.addAttribute("Username",user.getUsername());

        List<Comment> comments = commentService.getAllCommentByUid((id));
        Collections.reverse(comments);

        for(int i=0;i<comments.size();i++){
            int nid = Integer.valueOf(comments.get(i).getNid());
            String titleWithUrl = "<a href =\"../" + nid + "\">" + newsService.getNewsTitleById(nid) + "</a>";
            comments.get(i).setNid(titleWithUrl);
            //判断是否是回复，做出处理
            String tid = comments.get(i).getTid();
            if(tid == null || tid == "") {
                //什么都不做
            }else {
                String tName = userService.getUsernameById(Integer.valueOf(comments.get(i).getTid()));
                comments.get(i).setContext("回复<a href =\"../user/" + tid + "\">@" + tName + "</a>:" + comments.get(i).getContext());
            }
        }
        map.addAttribute("Comments",comments);
        //用户喜好列表
        String txt = "<ul>";//返回的html
        String tag = user.getPreference();
        StringTool stringTool = new StringTool();
        Map<String,Integer> tagmap = stringTool.StringToMap(tag);
        if(tagmap.size()<6) {
            txt = "<p>现在还不知道你的喜好，再多看看新闻吧。</p>";
        }else {
            tagmap.remove("明星");
            tagmap.remove("时尚");
            tagmap.remove("影视");
            tagmap.remove("宠物");
            tagmap.remove("生活");

            //将Map转化为List集合，List采用ArrayList
            List<Map.Entry<String, Integer>> list_Data = new ArrayList<Map.Entry<String,Integer>>(tagmap.entrySet());
            //通过Collections.sort(List I,Comparator c)方法进行排序
            Collections.sort(list_Data,new Comparator<Map.Entry<String, Integer>>() {

                @Override
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return (o2.getValue().compareTo(o1.getValue()));
                }
            });
            //按在总分数所占的比重设置li的width,最长的宽度为186px,除以所占百分比就是总长度
            double total = 0;//总分数
            for(int i=0;i<list_Data.size();i++){
                total += list_Data.get(i).getValue();
            }
            double width = 186/(list_Data.get(0).getValue()/total);
            for(int i=0;i<list_Data.size();i++){
                double w = (list_Data.get(i).getValue()/total)*width;
                txt += "<li style=\"width: " + String.format("%.2f", w) + "px\">" + list_Data.get(i).getKey() + "</li>";
            }
            txt += "</ul>";
        }

        map.addAttribute("tag",txt);

        return "user";
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLoginHtml(){
        return "login";
    }

    @RequestMapping(value = "/signup",method = RequestMethod.GET)
    public String toSignupHtml(){
        return "signup";
    }

    @RequestMapping(value = "/logincheck",method = RequestMethod.POST)
    public String loginCheck(HttpServletRequest request,ModelMap map){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.getUserByUP(username,password);
        if(user != null){
            request.getSession().setAttribute("user",user);
            //如果是第一次登陆，则选择初喜好
            StringTool stringTool = new StringTool();
            Map<String, Integer> preMap = stringTool.StringToMap(user.getPreference());
            if(preMap.size()<6){
                List<News> newsList = newsService.getAllNewsByTypeIsNotNull();
                Set<String>[] sets = stringTool.getlabel(newsList);
                String [] txt = new String[]{"","","","",""};
                for (int i=0;i <sets.length;i++) {
                    for (String s:sets[i]) {
                        txt[i] += "<button type=\"button\" class=\"btn btn-default\">"+ s +"</button>";
                    }
                }
                map.addAttribute("mx",txt[0]);
                map.addAttribute("ss",txt[1]);
                map.addAttribute("ys",txt[2]);
                map.addAttribute("cw",txt[3]);
                map.addAttribute("sh",txt[4]);
                return "firstlogin";
            }
            return "redirect:/";
        }
        map.addAttribute("msg","账号密码错误");
        return "login";
    }

    @RequestMapping(value = "/signupcheck",method = RequestMethod.POST)
    public String signupCheck(HttpServletRequest request,ModelMap map){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.getUserByUsername(username);
        if(user == null){
            User u = new User();
            u.setUsername(username);
            u.setPassword(password);
            u.setPreference("明星=1,时尚=1,影视=1,宠物=1,生活=1");//设置用户初始喜好
            userService.saveUser(u);
            map.addAttribute("msg","注册成功，请登录");
            return "login";
        }
        map.addAttribute("msg","用户已被注册");
        return "signup";
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logoutUser(HttpSession session){
        session.setAttribute("user",null);
        return "redirect:/";
    }

    @RequestMapping(value = "/setUserPreference",method = RequestMethod.GET)
    public String setUserPreference(@RequestParam(value = "preference",required = false)String preference,HttpSession session){
        if(preference!=null&&!preference.equals("")) {
            User user = (User) session.getAttribute("user");
            String s = "";
            if("明星,时尚,影视,宠物,生活".equals(preference)){
                s = "明星=1,时尚=1,影视=1,宠物=1,生活=1";
            }else{
                StringTool stringTool = new StringTool();
                s = stringTool.typeAdd(user.getPreference(), preference, 5);
            }
            user.setPreference(s);
            userService.saveUser(user);
        }
        return "redirect:/";
    }
}
